<?php

class Paper extends CI_Controller {

	public function __construct() {
		parent::__construct();

		$this->load->helper(array('form','url'));
		$this->cond = "";
		$this->notice = "";
		$this->from = "";
		$this->page = 1;
	}

	public function _remap($method, $params)
	{
		$u = Current_User::user();
		if(!$u) {
			$this->load->view('pages/user/logout', array('info' => '请先登录系统'));
		}else{
			$role = Current_User::my_role();
			if($role == Current_User::$administrtor) $this->is_admin = true;
			else $this->is_admin = false;
		    if (method_exists($this, $method))
		    {
		        return call_user_func_array(array($this, $method), $params);
		    }
			//$this->$method();
		}
	}
	
	public function index() {

		$u = Current_User::user();
		if($u == "")
		{
			redirect("./user/login");
		}
		$name = $u->account;

		//load the model and get results
		$this->load->model('paper_model');

		$this->load->library('pagination');
		$config['base_url'] = site_url('paper/paper/search');
		$config['per_page'] = 20;
		$config['uri_segment'] = 4; 
		
		$config['full_tag_open'] = '<p>';
		$config['full_tag_close'] = '</p>';

		$config['first_link'] = '首页';
		$config['last_link'] = '尾页';
		$config['next_link'] = '下一页';
		$config['prev_link'] = '上一页';

		//先解锁过期的
		$this->paper_model->unlock_timeout(); 

		$config['total_rows'] = $this->paper_model->get_papers_num($this->cond);
		
		$this->pagination->initialize($config);	            

		if($this->from == "")
		{
			$page = $this->uri->segment(4) ? $this->uri->segment(4) : 1;
		} else {
			$page = $this->page;
		}

		$tmp = $this->paper_model->get_papers($config['per_page'],$page,$this->cond);
		if(!empty($tmp))
		{
			$paper_rets = $tmp->result_array();
		} else {
			$paper_rets = array();
		}
		log_message("debug","paper_rets=".json_encode($paper_rets));
		$n = count($paper_rets);
		$data['results'] = "";
		for($i=0;$i<$n;$i++)
		{
			// create downloads link
			$file = $this->config->base_url()."paper/paper/download/".$page."/".$paper_rets[$i]['file_id'];
			$opera = '';
			
			// create lock link
			$lock = $this->config->base_url()."paper/paper/lock/".$page."/".$paper_rets[$i]['file_id'];
			$href = "<span class='green'>未上锁</span>";
			if($paper_rets[$i]['lock_state']=='lock')
			{
				$href = "<span class='red'>已上锁</span>";
				if($name == $paper_rets[$i]['download_user'] || $this->is_admin)
				{
					$opera .= "<a href='#myModal' role='button' onclick='pre_download(\"".$file."\");' data-toggle='modal' class='icon-arrow-down' title='下载'></a>&nbsp;|&nbsp;";
					$opera .= "<a href=".$lock." class='icon-lock' title='解锁'></a>&nbsp;|&nbsp;";
				}
			}else{
				$opera .= "<a href='#myModal' role='button' onclick='pre_download(\"".$file."\");' data-toggle='modal' class='icon-arrow-down' title='下载'></a>&nbsp;|&nbsp;";
			}

			$paper_rets[$i]['lock_state'] = $href;
			$paper_rets[$i]['opera'] = $opera.
				'<a class="icon-edit" title="编辑" href="/paper/upload/edit/'.$paper_rets[$i]['file_id'].'"></a>&nbsp;|&nbsp;'.
				'<a class="icon-trash" title="删除" href="/paper/upload/del/'.$paper_rets[$i]['file_id'].'" onclick="if(!confirm(\'确认删除吗？\')) return false;"></a>';

			#$data['results'][$i]['file_name'] = $paper_rets[$i]['file_name'];
			$data['results'][$i]['file_name'] = $paper_rets[$i]['file_name']."<br> <a href=\"/paper/preview/index/".$paper_rets[$i]['file_name']."\" target=\"_blank\" >预览</a>";
			$data['results'][$i]['file_info'] = "指导老师：".$paper_rets[$i]['teacher']."<br>学校：".$paper_rets[$i]['school_name'].
			"<br>专业：".$paper_rets[$i]['pro_name']."<br>层次：".$paper_rets[$i]['level_name']."<br>字数：".$paper_rets[$i]['words'];
			$data['results'][$i]['count'] = $paper_rets[$i]['count'];
			$data['results'][$i]['lock_info'] = "锁定状态：".$paper_rets[$i]['lock_state']."<br>".($paper_rets[$i]['download_user'] != "" ? "最近下载人：<b>".$paper_rets[$i]['download_user'] : "").
			"</b><br>".($paper_rets[$i]['download_time'] != "" ? "下载时间：".$paper_rets[$i]['download_time']: "")."<br>".($paper_rets[$i]['lock_time'] != "0000-00-00 00:00:00" ? "锁定截止时间：<b>".($paper_rets[$i]['lock_time'] != null ? $paper_rets[$i]['lock_time'] : "") : "")."</b>";
			$data['results'][$i]['upload_info'] = "上传人：".$paper_rets[$i]['upload_user']."<br>上传时间：".$paper_rets[$i]['upload_time'];
			$data['results'][$i]['use_school'] = $paper_rets[$i]['use_school'];
			$data['results'][$i]['opera'] = $paper_rets[$i]['opera'];

		}       

		// print_r($data["results"]);

		// load the HTML Table Class
		$this->load->library('table');
		$tmpl = array ( 'table_open'  => '<table border="1" cellpadding="0" cellspacing="0" class="mytable">' );
		$this->table->set_template($tmpl);
 
		$this->table->set_heading('文件名', '论文信息','下载次数','锁定信息','上传信息','用于高校','操作');

		// load search selections
		$data['schools'] = $this->paper_model->get_school();
		$data['professions'] = $this->paper_model->get_profession();
		$data['levels'] = $this->paper_model->get_level();
		$data['notice'] = $this->notice != "" ? "提示：".$this->notice : $this->notice;
		            
		// load the view
		$this->load->view('pages/paper/paper', $data);
	}

	public function search() {
		$cond_0 = $this->input->post('school') ? "school_id=".$this->input->post('school') : "1";
		$cond_1 = $this->input->post('level') ? "level_id=".$this->input->post('level') : "1";
		$cond_2 = $this->input->post('profession') ? "profession_id=".$this->input->post('profession') : "1";
		$cond_3 = $this->input->post('file_name') ? "file_name like \"%".$this->input->post('file_name')."%\"" : "1";

		$this->cond = "where ".$cond_0." and ".$cond_1." and ".$cond_2." and ".$cond_3;
		log_message('debug','cond='.$this->cond);

		$this->index();
	}

	public function download($page,$id) {
		$this->load->model('paper_model');
		$row = $this->paper_model->get_paper_from_id($id)->row();

		$use_school = $this->input->post("use_school");
		$lock_time = $this->input->post("lock_time");
 		log_message("debug","file id:".$id.'---'.$use_school.'---lock_time='.$lock_time);

		$u = Current_User::user();
		$name = $u->account;

		// check permission
		if (($row->lock_state=='lock') && ($name!=$row->download_user) && !$this->is_admin)
		{
 			log_message("debug","lock !!!");
			// lock
			$this->notice = "该下载文件被用户 $row->download_user 锁定";
			#redirect("./paper/paper");
			$this->page = $page;
			$this->from = "indirect";
			$this->index();
			return;
		}
		
		//pop here!!

		// redirect to download file
		$local_path = "/data/papers/file/".$row->file_name;

		log_message("debug","local_path:".$local_path);

		//$local_path = realpath(dirname(__FILE__).'/../../../'.$path);
		$file_path = $this->config->base_url().substr($local_path,1);

		log_message("debug","file_path:".$file_path);

		$this->page = $page;
		$this->from = "indirect";
		if(!file_exists($local_path))
		{
			$this->notice = "该文件不存在，请联系管理员";
			$this->index();
		} else {
			log_message("debug","begin download");

			// update database for download user & lock file
			//$save_data = array('download_user' =>$name,'lock_state' => "lock",'use_school' => $use_school, 'lock_time' => date("Y-m-d H:i:s",strtotime($lock_time)),'download_time' => date("Y-m-d H:i:s",time()));
			
			$this->paper_model->lock_paper($name, $use_school,date("Y-m-d H:i:s",strtotime($lock_time)),date("Y-m-d H:i:s",time()),$id);
			$this->paper_model->add_download_count($id);
			$this->index();
			//log_message("debug","save_data:".json_encode($save_data));
			//redirect($file_path);

			//redirect("paper/paper");
			
			$this->load->helper('download');
			$data = file_get_contents("$local_path"); // 读文件内容
			$filename = $row->file_name;
			
			
			force_download($filename, $data);
		}

	}

	public function lock($page,$id) {
		$this->load->model('paper_model');
		$row = $this->paper_model->get_paper_from_id($id)->row();

		$u = Current_User::user();
		$name = $u->account;

		if($row->lock_state=='lock')
		{
			if($name==$row->download_user || $this->is_admin)
			{
				$this->paper_model->unlock_paper($id,"\"$name\"");
			}
		}
		$this->page = $page;
		$this->from = "indirect";
		//$this->index();
		redirect("paper/paper");
	}
}
